//! 网络管理模块
//! 
//! net_manager.rs
//! 
//! (RUST) alone
//! 
//! Create time: 2025-09-26		alone
//! Update time: 2025-09-29		alone
//! 

use anyhow::Ok;
use dashmap::DashMap;
use tokio::sync::broadcast;
use tracing::{error, info};
use uuid::Uuid;

use crate::{common::{pubsub::Subscribe, transport::Connector, utils::Utils}, conf::AppConfig, events::Events, net::{tcp_client::TcpClient, tcp_server::TcpServer, NetEvent}};

#[derive(Debug, Clone)]
pub struct NetManager 
{
	/// 客户端
	client: TcpClient,
	/// 服务端
	server: TcpServer,
	/// 应用程序配置
	config: AppConfig,
	/// 客户端列表
	clients: std::sync::Arc<DashMap<Uuid, TcpClient>>,
	/// 广播订阅事件
	tx_evt: broadcast::Sender<Events>,
}

impl NetManager
{
	pub fn new(config: AppConfig) 
		-> Self
	{
		let (tx, _) = tokio::sync::broadcast::channel(100);
		Self 
		{ 
			client: TcpClient::new(format!("{}:{}", 
				config.mode.client.ip, 
				config.mode.client.port)), 
			server: TcpServer::new(format!("{}:{}", 
				config.mode.server.ip,
				config.mode.server.port).parse().unwrap()),
			config,
			clients: std::sync::Arc::new(DashMap::new()),
			tx_evt: tx,
		}
	}

	pub async fn initialize(&self) 
		-> anyhow::Result<()>
	{
		// 是否打开客户端
		if self.config.mode.client.open
		{
			let oneself = self.clone();
			tokio::spawn(async move {
				oneself.socket_client_subscribe().await;
			});
			
			Utils::sleep(1);

			if let Err(e) = self.client.connect().await
			{
				error!("{e}");
			}
			else  
			{
				info!("连接地址[{}]连接成功！！！", self.client.address());
			}
		}

		// 是否打开服务端
		if self.config.mode.server.open
		{
			let oneself = self.clone();
			tokio::spawn(async move {
				oneself.socket_server_subscribe().await;
			});

			Utils::sleep(1);
			
			let oneself = self.server.clone();
			tokio::spawn(async move {
				if let Err(e) = oneself.start().await 
				{
					let _ = oneself.event().send(NetEvent::ListenedFailed(e.to_string()));
				}
			});
		}
		
		Ok(())
	}

	async fn socket_client_subscribe(&self)
	{
		let mut receiver = self.client.subscribe();
		while let Result::Ok(event) = receiver.recv().await
		{
			match event 
			{
				NetEvent::RecvData(data_package) =>
				{
					let _ = self.tx_evt.send(Events::HandlerData(data_package));
				}
				NetEvent::Disconnected(client)  => 
				{
					info!("断开与服务器[{}]地址的连接！！！", client.address());
					if let Err(e) = client.connect().await
					{
						error!("{e}");
					}
					else  
					{
						info!("连接地址[{}]连接成功！！！", client.address());
					}
				}
				NetEvent::ConnectedFailed => 
				{
					let client = self.client.clone();
					// 连接失败，定时多少秒后重新连接
					tokio::spawn(async move {
						info!("在 3s 后将重连[{}]地址！！！", client.address());
						Utils::sleep(3);
						if let Err(e) = client.connect().await
						{
							error!("{e}");
						}
						else  
						{
							info!("连接地址[{}]连接成功！！！", client.address());
						}
					});
				}
				_ =>
				{

				}
			}
		}
	}

	async fn socket_server_subscribe(&self)
	{
		let mut receiver = self.server.subscribe();
		while let Result::Ok(event) = receiver.recv().await
		{
			match event 
			{
				NetEvent::RecvData(data_package) =>
				{
					let _ = self.tx_evt.send(Events::HandlerData(data_package));
				}
				NetEvent::Disconnected(client)  => 
				{
					info!("服务器断开与[{}]地址的连接！！！:(", client.address());
					self.unregister(&client.uuid());
				}
				NetEvent::Accept(client) => 
				{
					info!("收到来自[{}]地址的连接，已将连接设备注册！！！:)", client.address());
					self.register(client);
				}
				_ =>
				{

				}
			}
		}
	}

	/// 注册设备
	fn register(&self, client: TcpClient)
	{
		self.clients.insert(client.uuid(), client);
	}

	/// 移除注册设备
	fn unregister(&self, id: &Uuid) 
	{
        self.clients.remove(id);
    }

}

impl Subscribe for NetManager 
{
	type Event = Events;

	fn subscribe(&self) -> 
		broadcast::Receiver<Self::Event> 
	{
		self.tx_evt.subscribe()	
	}
}